package com.chenyuxin.ilp.ai.tool;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyuxin.ilp.mapper.plan.PlanMapper;
import com.chenyuxin.ilp.model.entity.plan.Plan;
import com.chenyuxin.ilp.model.pojo.Result;
import com.chenyuxin.ilp.model.vo.plan.DailyPlanDTO;
import com.chenyuxin.ilp.model.vo.plan.DayPlanVo;
import com.chenyuxin.ilp.model.vo.plan.MonthPlanDto;
import com.chenyuxin.ilp.service.plan.PlanService;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PlanAnalyseTool {
    @Autowired
    private PlanService planService;
    @Autowired
    private PlanMapper planMapper;

    @Tool("获取今天日期")
    public String getDate(){
        return LocalDateTime.now().toString();
    }
    @Tool("获取指定日期的用户学习计划")
    public List<DayPlanVo> getDayLearningPlan(@P("年")Integer year,@P("月")Integer month,@P("日")Integer day,@P("用户id")String userId){
        Result res = planService.selectPlanByDay(day, month, year, userId);
        List<DayPlanVo> data = (List<DayPlanVo>) res.getData();
        return data;
    }
    @Tool("一段日期的范围内每天的计划")
    public Map<LocalDate, List<MonthPlanDto>> getPeriodLearningPlan(@P("查询起始时间")LocalDateTime startTime,@P("查询末尾时间")LocalDateTime endTime,@P("用户id")String userId){
        LambdaQueryWrapper<Plan> planWrapper = new LambdaQueryWrapper<>();
        planWrapper.eq(Plan::getUserId,userId)
                .between(Plan::getStartTime,startTime,endTime);
        List<Plan> plans = planMapper.selectList(planWrapper);
        Map<LocalDate, List<MonthPlanDto>> map = plans.stream()
                .collect(Collectors.groupingBy(
                        plan -> plan.getStartTime().toLocalDate(),
                        Collectors.mapping(plan -> BeanUtil.copyProperties(plan, MonthPlanDto.class), Collectors.toList())
                ));
        List<DailyPlanDTO> result = new ArrayList<>();
        for (LocalDate date = startTime.toLocalDate(); !date.isAfter(endTime.toLocalDate()); date = date.plusDays(1)) {
            List<MonthPlanDto> list = map.getOrDefault(date, new ArrayList<>());
            result.add(new DailyPlanDTO(date, list));
        }
        return map;
    }
}
